//
//  FBDPhotoAlbumViewController.m
//  iOS9Sample-Photos
//
//  Created by feng on 2018/4/7.
//  Copyright © 2018年 小码哥. All rights reserved.
//
/**
 *
 * 相册 tableView
 *
 */
#import "FBDPhotoAlbumViewController.h"
#import "FBDPictureViewController.h"
//#import <Photos/Photos.h>
#import "FBDPhotoManger.h"

#define ScreenW [UIScreen mainScreen].bounds.size.width
#define ScreenH [UIScreen mainScreen].bounds.size.height

@interface FBDPhotoAlbumViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView*myTableView;
@property(nonatomic,strong)NSMutableArray*listAlbumArray;
@end

@implementation FBDPhotoAlbumViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title=@"所有的相册总集";
    UIBarButtonItem* rightButtonItem=[[UIBarButtonItem  alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(backButtonAction)];
    self.navigationItem.rightBarButtonItem=rightButtonItem;
    [self setMyViewOfChidrenUI];
    
    [self getAllAlbums];
    
}


//得到所有的相册
-(void)getAllAlbums
{
    [[FBDPhotoManger shareManager] searchUserMobileAllCollectionComplained:^(NSMutableArray<PHAssetCollection *> *assetCollectionArray) {
        _listAlbumArray=assetCollectionArray;
        [_myTableView reloadData];
    }];

}

/**
 *  遍历相簿中的所有图片 这里用来查找封面了
 *  @param assetCollection 相簿
 *  @param original        是否要原图
 */
- (void)enumerateAssetsInAssetCollection:(PHAssetCollection *)assetCollection original:(BOOL)original blcok:(void (^)(UIImage *__nullable result, NSInteger totalPic))resultHandler
{
    NSLog(@"相簿名:%@", assetCollection.localizedTitle);
    
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    // 同步获得图片, 只会返回1张图片
    options.synchronous = YES;
    
    // 获得某个相簿中的所有PHAsset对象
    PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
//    for (PHAsset *asset in assets) {
        // 是否要原图
    PHAsset* asset=[assets lastObject];
        CGSize size = original ? CGSizeMake(asset.pixelWidth, asset.pixelHeight) : CGSizeMake(asset.pixelWidth/10, asset.pixelHeight/10);
        
        // 从asset中获得图片
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            NSLog(@"%@", result);
            if (resultHandler) {
                resultHandler(result,assets.count);
            }
        }];
//    }
}




-(void)backButtonAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)setMyViewOfChidrenUI
{
    _myTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenW, ScreenH-64) style:UITableViewStylePlain];
    _myTableView.delegate=self;
    _myTableView.dataSource=self;
    
    _myTableView.rowHeight=90;
    _myTableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:_myTableView];

    
}

#pragma mark ---UITableViewDataSource&&UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _listAlbumArray.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* indetifier=@"MyCells";
    UITableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:indetifier];
    if (!cell)
    {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indetifier ];
        cell.imageView.image = [UIImage imageNamed:@"plun_hicon.png"];
        cell.selectionStyle=0;
        UIImageView*leftImageView=[[UIImageView alloc]initWithFrame:CGRectMake(20, 5, 80, 80)];
        
        leftImageView.tag=100;
        [cell.contentView addSubview:leftImageView];
        UILabel*leftTitleLabel=[[UILabel alloc]initWithFrame:CGRectMake(120, 20, 200, 20)];
        
        leftTitleLabel.tag=110;
        [cell.contentView addSubview:leftTitleLabel];
        UILabel*leftNumLabel=[[UILabel alloc]initWithFrame:CGRectMake(120, 50, 200, 20)];
        
        leftNumLabel.tag=120;
        [cell.contentView addSubview:leftNumLabel];
    }
    
    PHAssetCollection*indexAssetCollection= _listAlbumArray[indexPath.row];
    UIImageView* leftImageAlbumView=[cell viewWithTag:100];
    UILabel* leftTitleLabel=[cell viewWithTag:110];
    UILabel* leftNumLabel=[cell viewWithTag:120];
    leftTitleLabel.text=indexAssetCollection.localizedTitle;

    [[FBDPhotoManger shareManager]  searchLastImagesInCollection:indexAssetCollection  withBlcok:^(UIImage * _Nullable result,NSInteger totalPic) {
        leftImageAlbumView.image=result;
        leftNumLabel.text=[NSString stringWithFormat:@"有%ld张相片或视频",totalPic];
    }];
    
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray*tempArray=[NSMutableArray array];
    NSInteger row=indexPath.row;
    PHAssetCollection*assetCollection=_listAlbumArray[row];
    PHFetchResult<PHAsset *> *assetResult= [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
    
    for (PHAsset*asset  in assetResult) {
        if (asset.mediaType != PHAssetMediaTypeImage) continue;
        [tempArray addObject:asset];
    }
    
//    PHFetchResult<PHAsset *> *assetResult = [PHAsset fetchAssetsInAssetCollection:collection options:nil];
//    for (PHAsset *asset in assetResult) {
//        // 过滤非图片
//        if (asset.mediaType != PHAssetMediaTypeImage) continue;
//
//        [_listPictureArray addObject:asset];
//
//
//
//
//
//    }
    
    FBDPictureViewController*pictureVC=[[FBDPictureViewController alloc]init];
    
    pictureVC.pictureListArray=tempArray;
    
    [self.navigationController pushViewController:pictureVC animated:YES];
    
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end
